package top.continew.admin.controller.business;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.shengchao.examstar.rpc.base.PageResult;
import cn.shengchao.examstar.rpc.product.api.ICourseNodesRpc;
import cn.shengchao.examstar.rpc.product.api.ICourseRpc;
import cn.shengchao.examstar.rpc.product.api.IVideoHandle;
import cn.shengchao.examstar.rpc.product.req.CourseNodeConfig;
import cn.shengchao.examstar.rpc.product.req.CourseQueryPage;
import cn.shengchao.examstar.rpc.product.req.SaveCourseInfo;
import cn.shengchao.examstar.rpc.product.req.SaveCourseNodes;
import cn.shengchao.examstar.rpc.product.res.CourseList;
import cn.shengchao.examstar.rpc.product.res.CourseNodesTree;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.GetVideoInfoRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoInfoResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import top.continew.admin.common.context.UserContextHolder;
import top.continew.admin.controller.business.util.NoRedirectSimpleClientHttpRequestFactory;
import top.continew.starter.web.model.R;
import ws.schild.jave.EncoderException;
import ws.schild.jave.InputFormatException;
import ws.schild.jave.MultimediaObject;

import java.net.MalformedURLException;
import java.net.URL;
import java.time.Duration;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutionException;

/**
 * 课程 API
 *
 * @author sheng_chao
 * @since 2025/03/06 20:02
 */
@Tag(name = "课程 API")
@RestController
@RequestMapping("/course")
public class CourseController {

    @DubboReference
    private ICourseRpc iCourseRpc;

    @DubboReference
    private ICourseNodesRpc iCourseNodesRpc;

    @DubboReference(async = true, timeout = 50000, retries = 0)
    private IVideoHandle iVideoHandle;

    @GetMapping("video/handle")
    @Operation(summary = "处理视频", description = "处理视频")
    public R handleVideoTask() {
        iVideoHandle.handleVideoTask();
        return R.ok();
    }

    @GetMapping
    @Operation(summary = "获取课程列表", description = "获取课程列表")
    public PageResult<CourseList> getCourseList(CourseQueryPage courseQueryPage) {
        return iCourseRpc.getCourseList(courseQueryPage);
    }

    @GetMapping("{id}")
    @Operation(summary = "获取课程编辑信息", description = "获取课程编辑信息")
    public SaveCourseInfo getInfo(@PathVariable Long id) {
        return iCourseRpc.getCourseInfo(id);
    }

    @PostMapping
    @Operation(summary = "保存课程", description = "保存课程")
    public R saveCourse(@RequestBody SaveCourseInfo saveCourseInfo) {
        iCourseRpc.editCourse(saveCourseInfo);
        return R.ok();
    }

    @PostMapping("changeStatus/{id}")
    @Operation(summary = "修改课程状态", description = "修改课程状态")
    public R changeStatus(@PathVariable("id") Long courseId) {
        iCourseRpc.changeStatus(courseId);
        return R.ok();
    }

    @Operation(summary = "保存课程配置", description = "保存课程配置")
    @PostMapping("/config")
    public R saveCourseConfig(@RequestBody CourseNodeConfig courseNodeConfig) {
        courseNodeConfig.setUserId(UserContextHolder.getUserId());
        iCourseNodesRpc.editCourseNodeConfig(courseNodeConfig);
        return R.ok();
    }

    @GetMapping("{id}/config")
    @Operation(summary = "获取课程配置", description = "获取课程配置")
    public CourseNodeConfig getConfig(@PathVariable Long id) {
        return iCourseNodesRpc.getCourseNodeConfig(id);
    }

    @DeleteMapping("{id}")
    @Operation(summary = "删除课程", description = "删除课程")
    public R deleteCourse(@PathVariable long id) {
        iCourseRpc.deleteCourse(id);
        return R.ok();
    }

    @GetMapping("courseNodes/byKnowledge")
    @Operation(summary = "根据知识点生成课程章节", description = "根据知识点生成课程章节")
    public void getCourseNodesByKnowledge(@RequestParam Long courseId, String knowledgePointPath) {
        iCourseNodesRpc.generateChapter(courseId, knowledgePointPath);
    }

    @PostMapping("courseNodes")
    @Operation(summary = "保存课程章节", description = "保存课程章节")
    public R saveCourseNodes(@RequestBody SaveCourseNodes saveCourseNodes) throws ExecutionException, InterruptedException, ClientException {
        if (StrUtil.isNotEmpty(saveCourseNodes.getVideoId())) {
            DefaultProfile profile = DefaultProfile.getProfile("cn-shenzhen",
                    "LTAIBabaYDfy5oiy",
                    "tn987BbDeppXLp7mthEwniFVC9FhQh");
            IAcsClient client = new DefaultAcsClient(profile);
            GetVideoInfoRequest request = new GetVideoInfoRequest();
            request.setVideoId(String.valueOf(saveCourseNodes.getVideoId()));
            GetVideoInfoResponse response = client.getAcsResponse(request);
            if (response.getVideo() != null) {
                Float duration = response.getVideo().getDuration();
                saveCourseNodes.setDuration(Double.valueOf(duration));
            }
        }
        Long courseNodeId =iCourseNodesRpc.editCourseNodes(saveCourseNodes);
        return R.ok(courseNodeId);
    }

    @GetMapping("courseNodes/{id}")
    @Operation(summary = "课程章节详情", description = "课程章节详情")
    public SaveCourseNodes getCourseNodes(@PathVariable Long id) {
        return iCourseNodesRpc.getCourseNode(id);
    }

    @DeleteMapping("courseNodes/{id}")
    @Operation(summary = "删除章节", description = "删除章节")
    public R deleteCourseNodes(@PathVariable Long id) {
        iCourseNodesRpc.deleteCourseNodes(id);
        return R.ok();
    }

    @GetMapping("courseNodes/tree")
    @Operation(summary = "课程章节树", description = "课程章节树")
    public List<CourseNodesTree> getCourseNodesTree(Long courseId) {
        return iCourseNodesRpc.getCourseNodesTree(courseId);
    }

    public static void main(String[] args) {
        try {
            URL url = new URL("https://storage.star.91yunshi.cn/storage/video/star/a0b4683c218471f0bfbc7511978f0102.mp4");
            MultimediaObject multimediaObject = new MultimediaObject(url);
            long duration = (multimediaObject.getInfo().getDuration()) / 1000;
            System.out.println(duration);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
